#include "Int_ESP32.h"
#define RECEIVE_MAX_LENGTH 128
static uint8_t receive_buff[RECEIVE_MAX_LENGTH] = {0};
static uint16_t Length = 0;

#define NEW_RECEIVE_MAX_LENGTH 256
static uint8_t NEW_receive_buff[NEW_RECEIVE_MAX_LENGTH] = {0};
static uint16_t NEW_Length = 0;

#define Message_RECEIVE_MAX_LENGTH 256
static uint8_t Message_receive_buff[NEW_RECEIVE_MAX_LENGTH] = {0};
static uint16_t Message_Length = 0;
void Int_ESP32_Handler(void);

static uint8_t data[100] = {0};
uint8_t have = 0;
void Int_ESP32_SendCmd(uint8_t *data)
{
    memset(NEW_receive_buff, 0, NEW_Length);
    NEW_Length = 0;
    HAL_UART_Transmit(&huart2, (uint8_t *)data, strlen((char *)data), 1000);
    do
    {
        memset(receive_buff, 0, Length);
        Length = 0;
        HAL_UARTEx_ReceiveToIdle(&huart2, receive_buff, RECEIVE_MAX_LENGTH, &Length, 1000);
        memcpy(&NEW_receive_buff[NEW_Length], receive_buff, Length);
        NEW_Length += Length;
    } while (strstr((char *)receive_buff, "OK") == NULL && strstr((char *)receive_buff, "ERROR") == NULL);
    printf("Receive:%s\r\n", NEW_receive_buff);
    HAL_Delay(3000);
}
void Int_ESP32_Init(void)
{
    Int_ESP32_SendCmd("AT+RST=0\r\n");
    Int_ESP32_SendCmd("AT+GMR\r\n");
    Int_ESP32_SendCmd("AT+CWMODE=1\r\n");
    Int_ESP32_SendCmd("AT+CWJAP=\"ccss\",\"18545521340\"\r\n");
    Int_ESP32_SendCmd("AT+MQTTUSERCFG=0,1,\"aaa\",\"\",\"\",0,0,\"\"\r\n");
    Int_ESP32_SendCmd("AT+MQTTCONN=0,\"192.168.0.109\",1883,1\r\n");
    Int_ESP32_SendCmd("AT+MQTTPUB=0,\"chen\",\"陈爽\",1,0\r\n");
    Int_ESP32_SendCmd("AT+MQTTSUB=0,\"chen\",1\r\n");
}
void Int_ESP32_ReceiveData(void)
{
    memset((char *)Message_receive_buff, 0, Message_RECEIVE_MAX_LENGTH);
    Message_Length = 0;
    HAL_UARTEx_ReceiveToIdle(&huart2, Message_receive_buff, Message_RECEIVE_MAX_LENGTH, &Message_Length, 1000);
    if (Message_Length == 0)
    {
        return;
    }
    else if (strstr((char *)Message_receive_buff, "MQTTSUBRECV"))
    {
        memset((char *)data, 0, 100);
        char *lastComma = strrchr((char *)Message_receive_buff, ',');
        sprintf((char *)data, "%s", (char *)(lastComma + 1));
        printf("%s", data);
        Int_ESP32_Handler();
    }
    else
    {
        printf("Receive:%s\r\n", Message_receive_buff);
    }
}
void Int_ESP32_Handler(void)
{
    printf("Received data: [%s]\n", data); 
    if (strcmp((char *)data, "ON\r\n") == 0 || strcmp((char *)data, "OFF\r\n") == 0)
    {
        HAL_GPIO_TogglePin(LED1_GPIO_Port, LED1_Pin);
    }
}
